/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 * Description: yaml处理类
 */
#ifndef HAF_YAML_H
#define HAF_YAML_H

#include <string>
#include <fstream>
#include <iostream>
#include "yaml-cpp/yaml.h"

namespace Adsfi {
using HafYamlIterator = YAML::const_iterator;
using HafException = YAML::Exception;

class HafYaml {
public:
    explicit HafYaml(const std::string path)
    {
        std::ifstream fin(path);
        if (!fin) {
            std::clog << "Error: File corrupted or not exist.:" << path << std::endl;
        } else {
            fin.close();
        }
        node = YAML::LoadFile(path);
    }

    HafYaml() {}

    explicit HafYaml(const YAML::Node child)
    {
        this->node = child;
    }
    ~HafYaml() {};

    // indexing
    template <typename Key> const HafYaml operator[](const Key &keyName) const
    {
        return HafYaml(node[keyName]);
    }

    template <typename Key> HafYaml operator[](const Key &keyName)
    {
        return HafYaml(node[keyName]);
    }

    // access
    template <typename T> T As() const
    {
        return node.as<T>();
    }

    template <typename T> bool GetValue(const std::string &keyName, T &value) const
    {
        if (node[keyName]) {
            value = node[keyName].as<T>();
            return true;
        }
        return false;
    }

    HafYamlIterator begin() const
    {
        return node.begin();
    }

    HafYamlIterator end() const
    {
        return node.end();
    }

    bool IsSequence() const
    {
        return node.IsSequence();
    }

    bool IsDefined() const
    {
        return node.IsDefined();
    }

    size_t NodeSize() const
    {
        return node.size();
    }

    template <typename Key, typename Value>void SetModeValue(const Key &keyName, const Value &value)
    {
        node[keyName] = value;
        return;
    }

    YAML::Node GetNode() const
    {
        return node;
    }

    const YAML::Node HasKeyValue(const std::string &keyName) const
    {
        return node[keyName];
    }

private:
    YAML::Node node;
};
}

#endif // HAF_YAML_H
